package com.cqxyd.smartsite.util.v2;

import com.cqxyd.smartsite.pojo.v2.token.TokenParams;
import com.cqxyd.smartsite.pojo.v2.token.TokenRM;
import com.cqxyd.smartsite.pojo.v2.token.TokenResult;
import com.cqxyd.smartsite.util.JSONResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author Angus Yu
 * @date 2020-10-20 11:18
 */
@Service
public class BasicPostHelper {
    private final Logger logger = LoggerFactory.getLogger(BasicPostHelper.class);

    @Value("${base_url_new}")
    private String baseUrl;
    @Value("${taken_url}")
    private String takenUrl;
    @Value("${client_id}")
    private String clientId;
    @Value("${client_secret}")
    private String clientSecret;

    private JSONResult<TokenResult> getToken(){
        TokenParams params = new TokenParams();
        params.setClient_id(clientId);
        params.setClient_secret(clientSecret);
        params.setGrant_type("client_credentials");
        TokenRM rm = new TokenRM();
        rm.setParams(params);
        ObjectMapper mapper = new ObjectMapper();
        String requestStr;
        TokenResult tokenResult;
        try {
            requestStr = mapper.writeValueAsString(rm);
            JSONResult<String> result = postResult("",takenUrl,requestStr);
            if (result.isOK()){
                tokenResult = mapper.readValue(result.getData(),TokenResult.class);
            }else{
                return JSONResult.errorMsg(result.getMsg());
            }
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        }
        return JSONResult.ok(tokenResult);
    }

    public JSONResult<String> postRequest(String URL, String requestStr) {

        //获取Token
        JSONResult<TokenResult> tokenResult = getToken();
        String tokenStr = "";
        if (tokenResult.isOK()){
            TokenResult token = tokenResult.getData();
            if ("1".equals(token.getStatus().getCode()))
            {
                tokenStr = token.getCustom().getAccess_token();
            }else{
                return JSONResult.errorMsg(token.getStatus().getText());
            }
        }

        return postResult(tokenStr,URL,requestStr);
    }

    private JSONResult<String> postResult(String token,String URL, String requestStr){
        String jsonString = "";
        try {
            java.net.URL url = new URL(baseUrl + URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");

            if (!StringUtils.isEmpty(token)){
                connection.setRequestProperty("Authorization", "Bearer "+token);
            }
            connection.connect();
            PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
            out.println(requestStr);
            out.flush();
            out.close();
            if (connection.getResponseCode() == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String lines;
                StringBuffer sb = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "UTF-8");
                    sb.append(lines);
                }
                jsonString = sb.toString();
                reader.close();
                connection.disconnect();
            }else{
                connection.disconnect();
                String info ="使用POST发送信息失败，返回代码："+connection.getResponseCode() ;
                logger.error(info);
                return JSONResult.errorMsg(info);
            }

        } catch (MalformedURLException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return JSONResult.errorMsg(e.getMessage());
        }
        return JSONResult.ok(jsonString);
    }
}
